package com.mz3co.sysadmin.service.impl;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mz3co.sysadmin.dao.SysCustomerMapper;
import com.mz3co.sysadmin.model.SysAuthenticationInfo;
import com.mz3co.sysadmin.model.SysCompany;
import com.mz3co.sysadmin.model.SysCustomer;
import com.mz3co.sysadmin.model.SysCustomerExample;
import com.mz3co.sysadmin.model.SysCustomerExample.Criteria;
import com.mz3co.sysadmin.model.SysUsers;
import com.mz3co.sysadmin.model.ex.SysCustomerEx;
import com.mz3co.sysadmin.model.ex.SysEmployeeEx;
import com.mz3co.sysadmin.model.ex.SysUsersEx;
import com.mz3co.sysadmin.page.Page;
import com.mz3co.sysadmin.service.SessionService;
import com.mz3co.sysadmin.service.SysAuthenticationInfoService;
import com.mz3co.sysadmin.service.SysCompanyService;
import com.mz3co.sysadmin.service.SysCustomerService;
import com.mz3co.sysadmin.service.SysEmployeeService;
import com.mz3co.sysadmin.service.SysUsersService;
import com.mz3co.sysadmin.service.utils.CommonUtils;
import com.mz3co.sysadmin.service.utils.CriteriaUtils;
import com.mz3co.sysadmin.service.utils.DateJsonValueProcessor;
import com.mz3co.sysadmin.service.utils.ExportExcel;
import com.mz3co.sysadmin.service.utils.ReflectionUtils;
import com.mz3co.sysadmin.service.utils.SysConst;

@Service
public class SysCustomerServiceImpl implements SysCustomerService {

	@Autowired
	private SysCustomerMapper customerMapper;//SysCustomerMapperEx

	@Autowired
	private SysEmployeeService employeeService;
	
	@Autowired
	private SysCompanyService companyService;
	
	@Autowired
	private SysUsersService usersService;

	@Autowired
	private SysAuthenticationInfoService authenticationInfoService;
	
	@Autowired
	private SessionService sessionService;

	public Map<String, Object> getCusByPage(SysCustomerEx httpCustomer,
			Integer pageSize, Integer pageNow) {
		SysCustomerExample example = new SysCustomerExample();
		Criteria criteria = example.createCriteria();
		
		
		this.setCriteria(httpCustomer, criteria);
//		criteria.andCustomerIdIsNotNull();
		int totalrecords = customerMapper.countByExample(example);

		/**
		 * for my sql db
		 */
		Page page = new Page();

		page.setBegin((pageNow - 1) * pageSize);
		page.setLength(pageSize);

		example.setPage(page);

		List<SysCustomer> customers = customerMapper.selectByExample(example);

		/**
		 * for sql server db
		 */

		// example.setPageIndex(pageNow);
		// example.setPageSize(pageSize);
		// example.setOrderByClause(" customer_id desc");
		//
		// List<SysCustomer> customers = customerMapper.selectPage (example);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", totalrecords);
		if (totalrecords % pageSize == 0)
			map.put("totalPages", totalrecords / pageSize);
		else
			map.put("totalPages", totalrecords / pageSize + 1);
		JsonConfig config = new JsonConfig();
		config.setIgnoreDefaultExcludes(false);
		config.registerJsonValueProcessor(Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));

		map.put("rows", JSONArray.fromObject(
				this.createHttpCustomer(customers), config));
		return map;
	}

	private void setCriteria(SysCustomerEx httpCustomer,Criteria criteria){
		if (!StringUtils.isEmpty(httpCustomer.getCustomerName())) {
			criteria.andCustomerNameLike("%" + httpCustomer.getCustomerName()
					+ "%");
		}
		if (!StringUtils.isEmpty(httpCustomer.getCompanyName())) {
			criteria.andCompanyNameLike("%"
					+ httpCustomer.getCompanyName() + "%");
		}

		if (!StringUtils.isEmpty(httpCustomer.getCuonterManName())) {

			List<Integer> eIdList = employeeService.getEmployeeIds(httpCustomer
					.getCuonterManName());

			if (eIdList.size() == 0)
				eIdList.add(-1);

			criteria.andCounterManIn(eIdList);
		}

		
	}
	
	private List<SysCustomerEx> createHttpCustomer(List<SysCustomer> customerList) {

		List<SysCustomerEx> hcList = new ArrayList<SysCustomerEx>();

		for (SysCustomer c : customerList) {

			SysCustomerEx hc = new SysCustomerEx();
			// ReflectionUtils.parentToChild(c, hc);
			BeanUtils.copyProperties(c, hc);

			// 设置客户的负责人信息
			hc.setCuonterManName(SysConst.EMPLOYEE_MAP.get(c.getCounterMan()));
			hc.setCreatorName(SysConst.EMPLOYEE_MAP.get(c.getCreatorId()));

			hcList.add(hc);
		}

		return hcList;
	}

	// 判断用户的手机号是否存在
	public boolean isExistphone(SysCustomer customer) {

		SysCustomerExample example = new SysCustomerExample();

		example.or().andCellPhoneEqualTo(customer.getCellPhone());

		List<SysCustomer> customers = customerMapper.selectByExample(example);

//		if (customers.size() < 1)
//			return false;

		for (SysCustomer c : customers) {

			if (c.getCellPhone().equals(customer.getCellPhone())){
				
				customer.setCustomerId(c.getCustomerId());
				return true;
			}
				
		}

		return false;

	}

	// 判断用户的邮箱是否存在
	public boolean isExistEmail(SysCustomer customer) {
		if (StringUtils.isEmpty(customer.getEmail()) ){
			return false;
		}
		SysCustomerExample example = new SysCustomerExample();

		example.or().andEmailEqualTo(customer.getEmail());

		List<SysCustomer> customers = customerMapper.selectByExample(example);

//		if (customers.size() < 1)
//			return false;

		for (SysCustomer c : customers) {

			if (customer.getEmail().equals(c.getEmail()))
				customer.setCustomerId(c.getCustomerId());
				return true;
		}

		return false;

	}

	public void updateCompanyFullname(SysCustomer customer){
		
		SysCustomerExample example = new SysCustomerExample();

		example.or().andCompanyIdEqualTo(customer.getCompanyId());
		
		customerMapper.updateByExampleSelective(customer, example);
	}
	
	@Transactional
	public String update(SysCustomer customer) {

//		if (this.isExistphone(customer))
//			return "用户手机号已存在";
//
//		if (this.isExistEmail(customer))
//			return "用户邮箱已存在";

		// this.updateUsers(customer);
		if(customer.getCompanyId() == null )
			this.insertCompanyForCustomer(customer);
		
		this.setDefaultValue(customer);

		if (customerMapper.updateByPrimaryKeySelective(customer) < 1)
			return "修改失败,访问数据库失败！";

		return "修改成功！";
	}
	
	/**
	 * 新增员工，修改员工信息时,插入员工的单位信息，并返回插入的单位ID
	 * @param customer
	 */
	private void insertCompanyForCustomer(SysCustomer customer){
		
		if(customer.getCompanyName() == null || "".equals(customer.getCompanyName()))
			customer.setCompanyId(-1);
		else{//插入客户所作的公司信息
			
			SysCompany company =  new SysCompany();
			
			company.setCompanyName(customer.getCompanyName());
			companyService.insert(company);
			
			customer.setCompanyId(company.getCompanyId());
			
		}
	}

	private void setDefaultValue(SysCustomer customer){
	
		customer.setCreateTime(new Date());
		
		if(StringUtils.isEmpty(customer.getTarget()))
			customer.setTarget("其他");
		
		if(StringUtils.isEmpty(customer.getCustomerName()))
			customer.setCustomerName(customer.getCellPhone());
		
	}
	
	
	@Transactional
	public String insert(SysCustomerEx customer) {

		if (this.isExistphone(customer))
			return "用户手机号已存在";

		if (this.isExistEmail(customer))
			return "用户邮箱已存在";

	
		this.setSessionInfo(customer);
		
		//公司Id为空时插入客户对应的公司信息
		if(customer.getCompanyId() == null )
			this.insertCompanyForCustomer(customer);
		
		this.setDefaultValue(customer);
		customerMapper.insertSelectiveAndGetId(customer);
		
		
		this.insertUser(customer);
		
		return "新增客户成功！";
	}
	
	private void insertUser(SysCustomerEx customer){
		
		int customerId = customer.getCustomerId();
		
		SysUsers user = new SysUsers();
		
		
		/* 在添加员工信息时，将用户名添加到users表中 */
		if (customer.getCustomerName().length() > 0) {
			user.setUsername(customer.getCustomerName());
			user.setCreatetime(new Date());
			user.setType(customer.getType());
			user.setUserDetailId(customerId);
			usersService.insert(user);
//			usersMapper.insertSelectiveAndGetId(users);
//			uid = users.getId();
		}
		
		this.insertAuthenticationInfo(customer, user);
	
	}
	
	private void insertAuthenticationInfo(SysCustomerEx customer,SysUsers user){
		
		SysAuthenticationInfo info = new SysAuthenticationInfo();
		/* 将手机号和邮箱分别添加到授权表中，作为登录信息，密码默认为手机号后6位 */
		if (!StringUtils.isEmpty(customer.getCellPhone())) {
			info.setAccount(customer.getCellPhone());
			info.setUid(user.getId());
			info.setType("手机");
			info.setStatus("启用");
			int length = customer.getCellPhone().length();

			if(!StringUtils.isEmpty(customer.getPassword()))
				info.setPassword(customer.getPassword());
			
			else
				info.setPassword(customer.getCellPhone().substring(length - 6,
						length));
			
			authenticationInfoService.insert(info);

			if (!StringUtils.isEmpty(customer.getEmail())) {
				SysAuthenticationInfo info2 = new SysAuthenticationInfo();
				info2.setAccount(customer.getEmail());
				info2.setUid(user.getId());
				info2.setType("邮箱");
				info2.setStatus("启用");
				info2.setPassword(customer.getCellPhone().substring(length - 6,
						length));
				authenticationInfoService.insert(info2);
			}
		}
		
	}
	

	private void setSessionInfo(SysCustomer customer) {

		customer.setCreateTime(new Date());
		
		// 设置权限信息
		SysUsersEx user = sessionService.getSessionHttpUser();
		
		if(user == null){
			customer.setCreatorId( -1);
			customer.setCounterMan(-1);
			customer.setAccessGroup("-1");
			return;
		}
		
		customer.setCreatorId(user.getUserDetailId());
		customer.setCounterMan(user.getCounterMan());
		customer.setAccessGroup(user.getAccessGroup());
	
	

	}

	@Override
	public SysCustomer getCustomer(Integer customerId) {
		// TODO Auto-generated method stub
		return customerMapper.selectByPrimaryKey(customerId);
	}

	@Override
	public String setVIP(String ids, String type) {
		// TODO Auto-generated method stub
		SysCustomerExample example = new SysCustomerExample();

		example.or().andCustomerIdIn(CommonUtils.idsArrayToList(ids));

		SysCustomer customer = new SysCustomer();
		customer.setType(type);

		try {
			customerMapper.updateByExampleSelective(customer, example);
		} catch (Exception e) {
			return "访问数据库失败，vip设置失败！";
		}

		return "vip设置成功！";
	}

	@Override
	public String setCounterman(String ids, String employeeId) {

		// TODO Auto-generated method stub
		SysCustomerExample example = new SysCustomerExample();

		example.or().andCustomerIdIn(CommonUtils.idsArrayToList(ids));

		SysCustomer customer = new SysCustomer();
		customer.setCounterMan(Integer.parseInt(employeeId));

		try {
			customerMapper.updateByExampleSelective(customer, example);
		} catch (Exception e) {
			return "访问数据库失败，负责人设置失败！";
		}

		return "负责人设置成功！";
	}

	@Override
	public boolean isExistCellPhone( String cellPhone) {
		// TODO Auto-generated method stub

		SysCustomerExample example = new SysCustomerExample();


		example.or().andCellPhoneEqualTo(cellPhone);
		
		List<SysCustomer> customers = customerMapper.selectByExample(example);
		
		if(customers == null || customers.size() == 0)
			return false;
		
		return true;
	}

//	@Override
//	public Integer getCusIDBySC(SysCustomer sysCustomer) {
//		SysCustomerExample example = new SysCustomerExample();
//
//		example.or().andCustomerNameEqualTo(sysCustomer.getCustomerName());
//		example.or().andCellPhoneEqualTo(sysCustomer.getCellPhone());
//
//		List<SysCustomer> customers = customerMapper.selectByExample(example);
//
//		return customers.get(0).getCustomerId();
//
//	}

	@Override
	public String getCustomers(List<Integer> companyIds) {
		// TODO Auto-generated method stub
		
		StringBuffer result =  new StringBuffer("该单位下存在客户：");
		SysCustomerExample example = new SysCustomerExample();
		example.or().andCompanyIdIn(companyIds);
		
		List<SysCustomer> customers = customerMapper.selectByExample(example);
		
		if(customers == null || customers.size() == 0)
			return "";

		for(SysCustomer customer:customers)
			result.append(customer.getCustomerName() + "("+customer.getCompanyId()+"),");
		
		return result.toString();
	}

	@Override
	public String delete(String ids) {
		// TODO Auto-generated method stub
		if (StringUtils.isEmpty(ids))
			return "success";

		List<Integer>  customerIds = CommonUtils.idsArrayToList(ids);

		SysCustomerExample example = new SysCustomerExample();

		example.or().andCustomerIdIn(customerIds);
		
		return customerMapper.deleteByExample(example) == 0 ? "删除失败，数据库访问失败！"
				: "success";
	}

	@Override
	public SysCustomer getByCustomerName(String customerName) {
		// TODO Auto-generated method stub
		
		SysCustomerExample example = new SysCustomerExample();

		example.or().andCustomerNameEqualTo(customerName);


		List<SysCustomer> customers = customerMapper.selectByExample(example);
		
		if(customers == null || customers.size() == 0)
			return null;

		return customers.get(0);

	}

	@Override
	public SysCustomer getByCellPhone(String cellPhone) {
		
		SysCustomerExample example = new SysCustomerExample();

		example.or().andCellPhoneEqualTo(cellPhone);


		List<SysCustomer> customers = customerMapper.selectByExample(example);
		
		if(customers == null || customers.size() == 0)
			return null;

		return customers.get(0);

	}

	@Override
	public SysCustomer getByEmail(String email) {
		SysCustomerExample example = new SysCustomerExample();

		example.or().andEmailEqualTo(email);


		List<SysCustomer> customers = customerMapper.selectByExample(example);
		
		if(customers == null || customers.size() == 0)
			return null;

		return customers.get(0);
	}

	@Override
	public void exportExcel(SysCustomerEx customer, OutputStream os) {
		SysCustomerExample example = new SysCustomerExample();

		Criteria criteria = example.createCriteria();
		

		this.setCriteria(customer, criteria);
		example.setOrderByClause(" customer_id desc");
		List<SysCustomer>  listEmployeeEx= customerMapper.selectByExample(example);
		
		
		ExportExcel<SysCustomer> exportExcel = new ExportExcel<SysCustomer>();
		
		exportExcel.exportExcel("导出嘉宾信息", SysConst.ExcelConst.HEAD_SYSCUSTOMER,SysConst.ExcelConst.FIELDNAMES_SYSCUSTOMER, listEmployeeEx, os,"yyyy-MM-dd");


		
	}

	@Override
	public String update(String customerJSON) {
		if(StringUtils.isEmpty(customerJSON))
			return "修改失败，修改信息为空！";

		SysCustomerEx customer =  (SysCustomerEx)JSONObject.toBean(JSONObject.fromObject(customerJSON),SysCustomerEx.class );

		return this.update(customer);
	}

	@Override
	public String register(String customerJSON) {
		if(StringUtils.isEmpty(customerJSON))
			return "插入失败，注册信息为空！";
		
		
		SysCustomerEx customer =  (SysCustomerEx)JSONObject.toBean(JSONObject.fromObject(customerJSON),SysCustomerEx.class );
		
		customer.setType("嘉宾");
		
	
		return this.insert(customer);

	}


}
